package ua.kharkov.khpi.tarasenko.bach.web.command.common;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDAO;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to update settings.
 * 
 * @author oleksandr
 * 
 */
public class UpdateSettingsCommand extends Command {
	private static final Logger log = Logger
			.getLogger(UpdateSettingsCommand.class);

	private static final String ATTRIBUTE_USER_ID = "user_id";
	private static final String ATTRIBUTE_USER_FIRST_NAME = "user_firstName";
	private static final String ATTRIBUTE_USER_LAST_NAME = "user_lastName";
	private static final String ATTRIBUTE_USER_PHONE = "user_phone";
	private static final String ATTRIBUTE_LOCALE = "locale";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.COMMAND_SHOW_SETTINGS;
		String errorMessage = null;
		Connection conn = null;

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		UserDTO userDTO = extractUserDTO(request);
		int userId = userDTO.getId();
		if (userId < 1) {
			errorMessage = LRManager.getMessage("error_message.user_id_not_specified");
		} else {

			// Set specified locale
			String locale = request.getParameter(ATTRIBUTE_LOCALE);
			if ((locale != null) && (!locale.isEmpty())) {
				HttpSession session = request.getSession();
				Config.set(session, Config.FMT_LOCALE, locale);
				session.setAttribute(Constant.ATTRIBUTE_PREFERABLE_LOCALE,
						locale);
			}

			try {
				conn = ConnectionManager.getConnection();
				UserDAO userDAO = DAOFactory.getDAOFactory(
						DAOFactory.DAO_TYPE.MYSQL).getUserDAO(conn);

				int rowsUpdated = userDAO.update(userDTO);
				if (rowsUpdated < 1) {

					errorMessage = LRManager.getMessage("error_message.user_id_not_found");
				} else {

					// Everything is ok, so commit
					DBUtils.commitAndClose(conn);
					log.info("User with id=" + userId
							+ " successfuly updated his profile.");

					// Now update UserBean in user's session
					HttpSession session = request.getSession();
					UserBean userBean = (UserBean) session
							.getAttribute(Constant.ATTRIBUTE_USER_BEAN);
					userBean.setUserFirstName(userDTO.getFirstName());
				}
			} catch (EShopException e) {
				DBUtils.rollBackAndClose(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}

	/**
	 * Extract UserDTO object from request. If user's id is not specified it
	 * will be set -1!
	 * 
	 * @param request
	 * @return userDTO
	 */
	private UserDTO extractUserDTO(HttpServletRequest request) {
		String userIdString = request.getParameter(ATTRIBUTE_USER_ID);
		String userFirstName = request.getParameter(ATTRIBUTE_USER_FIRST_NAME);
		String userLastName = request.getParameter(ATTRIBUTE_USER_LAST_NAME);
		String userPhone = request.getParameter(ATTRIBUTE_USER_PHONE);
		if (log.isTraceEnabled()) {
			log.trace("Got parameters from request:\n\t" + ATTRIBUTE_USER_ID
					+ "=" + userIdString + ",\n\t" + ATTRIBUTE_USER_FIRST_NAME
					+ "=" + userFirstName + ",\n\t" + ATTRIBUTE_USER_LAST_NAME
					+ "=" + userLastName + ",\n\t" + ATTRIBUTE_USER_PHONE + "="
					+ userPhone);
		}

		UserDTO userDTO = new UserDTO();

		int userId = -1;
		if ((userIdString != null) && (!userIdString.isEmpty())) {
			userId = Integer.valueOf(userIdString);
		}
		userDTO.setId(userId);
		userDTO.setFirstName(userFirstName);
		userDTO.setLastName(userLastName);
		userDTO.setPhone(userPhone);

		return userDTO;
	}
}
